<!-- 帖子详情页面 -->
<template>
  <view class="container">
    <!-- 帖子的标题 -->
    <view class="title">{{ postData.text }}</view>
     <view v-if="isCurrentUserPost" class="delete-btn" @click="handleDelete">删除</view>
	
	 
    <!-- 发布者的头像和昵称 -->
    <view class="header">
      <!-- 发布者头像 -->
      <image class="avatar post-avatar" :src="postData.avatar" mode="aspectFill" />
      <!-- 发布者昵称 -->
      <view class="name post-name">{{ postData.name }}</view>
    </view>

    <!-- 帖子的详细内容 -->
    <view class="post-content">
      <!-- 帖子的文本内容 -->
      <view class="text">{{ postData.text }}</view>

      <!-- 九宫格的图片和视频 -->
      <view class="media-grid" v-if="postData.mediaList.length > 0">
        <view class="media-item" v-for="(item, index) in postData.mediaList" :key="index">
          <!-- 如果是图片，渲染图片 -->
          <image v-if="item.type === 'image'" class="media-image" :src="item.url" mode="aspectFill" />
          <!-- 如果是视频，渲染视频 -->
          <video v-if="item.type === 'video'" class="media-video" :src="item.url" controls />
        </view>
      </view>

      <!-- 添加操作栏 -->
      <view class="action-bar">
        <view class="action-item" @click="handleLike">
          <text class="iconfont icon-like" :class="{ 'liked': isLiked }"></text>
          <text class="action-count">{{ likeCount || '点赞' }}</text>
        </view>
        <view class="action-item" @click="toggleCommentInput">
          <text class="iconfont icon-comment"></text>
          <text class="action-count">{{ comments.length || '评论' }}</text>
        </view>
        <view class="action-item" @click="handleShare">
          <text class="iconfont icon-share"></text>
          <text class="action-count">分享</text>
        </view>
      </view>

      <!-- 点击评论区显示输入框 -->
      <view class="comment-action" @click="toggleCommentInput">
        <text class="comment-text">评论</text>
      </view>
    </view>

    <!-- 评论区 -->
    <view class="comments">
      <!-- 评论总数显示 -->
      <view class="comments-header">
        <text class="comments-count">评论 {{ comments.length }}</text>
      </view>

      <!-- 评论列表 -->
      <view v-for="(comment, index) in comments" :key="index" class="comment-item">
        <!-- 评论者信息区 -->
        <view class="comment-user">
          <image class="avatar" :src="comment.avatar" mode="aspectFill" />
          <view class="user-info">
            <text class="username">{{ comment.username }}</text>
            <text class="comment-time">{{ comment.commentTime }}</text>
          </view>
		    <view v-if="String(comment.userId) === String(currentUserId)" class="comment-delete" @click="handleCommentDelete(comment)">
		              删除
		            </view>
        </view>

        <!-- 评论内容 -->
        <view class="comment-content">
          <text class="comment-text">{{ comment.text }}</text>
        </view>

        <!-- 评论操作区 -->
        <view class="comment-actions">
          <view class="action-item" @click="toggleLike(comment)">
            <text class="iconfont icon-like"></text>
            <text class="action-text">{{ comment.commentGood || '点赞' }}</text>
          </view>
          <view class="action-item" @click="showReplyInput(index)">
            <text class="iconfont icon-reply"></text>
            <text class="action-text">回复</text>
          </view>
        </view>

        <!-- 回复列表 -->
        <view v-if="comment.replies && comment.replies.length > 0" class="replies">
          <view class="replies-header">
            <text class="replies-count">{{ comment.replies.length }}条回复</text>
          </view>
          <view v-for="(reply, rIndex) in comment.replies" :key="rIndex" class="reply-item">
            <view class="reply-user">
              <image class="avatar small" :src="reply.avatar" mode="aspectFill" />
              <view class="user-info">
                <view class="reply-user-info">
                  <text class="username">{{ reply.username }}</text>
                  <text class="reply-to">回复</text>
                  <text class="username">{{ comment.username }}</text>
                </view>
                <text class="comment-time">{{ reply.commentTime }}</text>
              </view>
            </view>
            <view class="reply-content">
              <text class="reply-text">{{ reply.text }}</text>
            </view>
          </view>
        </view>

        <!-- 回复输入框 -->
        <view v-if="replyingTo === index" class="reply-input-container">
          <input 
            v-model="newReply" 
            class="reply-input" 
            :placeholder="`回复 ${comment.username}...`"
            @confirm="submitReply(index)"
          />
          <button class="reply-btn" @click="submitReply(index)">发送</button>
        </view>
      </view>
    </view>

    <!-- 评论输入框 -->
    <view v-if="commenting" class="comment-input-container">
      <input 
        v-model="newComment" 
        class="comment-input" 
        placeholder="写下你的评论..." 
        @confirm="submitComment"
      />
      <button class="submit-btn" @click="submitComment">发送</button>
    </view>
  </view>
</template>

<script>
	import tool from '@/utils/tool.js'
	import postApi from '@/api/postApi.js'
	import commentApi from '@/api/CommentApi.js'
export default {
  data() {
    return {
      currentUser: {
        name: '张三', // 当前登录用户的昵称
        avatar: 'https://example.com/avatar.jpg', // 当前用户的头像
      },
      postId: null, // 存储传入的帖子id
      postData: {
        avatar: '',
        name: '',
        text: '',
        mediaList: []
      },
      comments: [], // 清空默认的测试数据，改为空数组
      newComment: '', // 当前输入的评论内容
      newReply: '', // 当前输入的回复内容
      replyingTo: null, // 当前正在回复的评论索引
      commenting: false, // 是否显示评论输入框
      commentTarget: null, // 当前目标评论，可能是整个帖子也可能是某个评论
      isCurrentUserPost: false, // 是否是当前用户的帖子
      currentUserId: '', // 当前用户的ID
      postUserId: '', // 帖子作者的ID
      isLiked: false,
      likeCount: 0,
    };
  },
  onLoad(options) {
    console.log('接收到的参数:', options); // 调试日志
    if (!options.id) {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    this.postId = options.id;
    this.fetchPostDetail();
	  // 获取当前用户ID
	    this.currentUserId = tool.data.get('userId');
	    console.log('当前用户ID:', this.currentUserId);
		    
		    // 如果没有获取到ID，可提示用户
		    if (!this.currentUserId) {
		      console.warn('未获取到用户ID');
		    }
  },
  onShow() {
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.switchTab({
          url: '/pages/mine/mine'
        });
        return;
      }
    }
  },
  methods: {
    // 获取帖子详情
    async fetchPostDetail() {
      try {
        console.log('请求帖子详情，ID:', this.postId);
        const response = await postApi.selectone({ id: this.postId });
        console.log('帖子详情响应:', response);

        if (response && response.data) {
          const post = response.data;
          this.postData = {
			  
            avatar: 'https://example.com/avatar.jpg',
            name: post.title || '匿名用户',
            text: post.text,
            mediaList: post.imageId ? post.imageId.map(url => ({
              type: 'image',
              url: url
            })) : []
          };
          
          // 保存帖子作者ID
          this.postUserId = post.userId;
          
          // 获取当前用户ID并判断是否是当前用户的帖子
          this.currentUserId = tool.data.get('userId');
          this.isCurrentUserPost = String(this.currentUserId) === String(this.postUserId);
          
          console.log('当前用户ID:', this.currentUserId);
          console.log('帖子作者ID:', this.postUserId);
          console.log('是否是当前用户的帖子:', this.isCurrentUserPost);
          
          // 获取帖子评论
          await this.fetchComments();
        } else {
          throw new Error('未获取到帖子数据');
        }
      } catch (error) {
        console.error('获取帖子详情失败：', error);
        uni.showToast({
          title: '获取详情失败',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },

    // 获取评论列表
    async fetchComments() {
      try {
        console.log('开始获取评论，postId:', this.postId);
        const response = await commentApi.selectComment({
          postId: this.postId
        });
        
        console.log('评论接口返回数据:', response);

        if (response && response.code === 1 && response.data) {
          console.log('开始处理评论数据');
          // 将后端返回的评论数据转换为前端所需的格式
          this.comments = response.data.map(comment => {
            console.log('处理单条评论:', comment);
            return {
              id: comment.id,
              avatar: comment.haedPortrait, // 修正拼写错误
              username: comment.username,
              text: comment.text,
              commentTime: comment.commentTime,
              commentGood: comment.commentGood || 0,
              replies: [],
              isReply: comment.replyId !== 0 && comment.replyId !== null
            };
          });

          console.log('转换后的评论数据:', this.comments);

          // 处理回复关系
          this.comments = this.comments.filter(comment => !comment.isReply);
          const replies = response.data.filter(comment => 
            comment.replyId !== 0 && comment.replyId !== null
          );

          console.log('过滤后的主评论:', this.comments);
          console.log('回复评论:', replies);

          // 将回复添加到对应的评论中
          replies.forEach(reply => {
            const parentComment = this.comments.find(c => c.id === reply.replyId);
            if (parentComment) {
              parentComment.replies.push({
                id: reply.id,
                avatar: reply.headPortrait || 'https://example.com/avatar.jpg', // 修正拼写错误
                username: reply.username,
                text: reply.text,
                commentTime: reply.commentTime,
                commentGood: reply.commentGood || 0
              });
            }
          });

          console.log('最终的评论数据:', this.comments);
        } else {
          console.log('接口返回数据格式不正确:', response);
        }
      } catch (error) {
        console.error('获取评论列表失败：', error);
        uni.showToast({
          title: '获取评论失败',
          icon: 'none'
        });
      }
    },

    // 修改提交评论方法，成功后刷新评论列表
    async submitComment() {
      if (this.newComment.trim() === '') {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none'
        });
        return;
      }

      try {
        const response = await commentApi.addComment({
          postId: this.postId,
          text: this.newComment
        });

        if (response && response.code === 1) {
          uni.showToast({
            title: '评论成功',
            icon: 'success'
          });

          this.newComment = ''; // 清空输入框
          this.commenting = false; // 隐藏输入框
          this.commentTarget = null; // 重置目标
          
          // 重新获取评论列表
          await this.fetchComments();
        } else {
          throw new Error(response.msg || '评论失败');
        }
      } catch (error) {
        console.error('发布评论失败：', error);
        uni.showToast({
          title: '评论失败',
          icon: 'none'
        });
      }
    },

    // 显示/隐藏评论输入框
    toggleCommentInput() {
      this.commenting = !this.commenting; // 切换评论输入框的显示状态
      if (this.commenting) {
        this.commentTarget = 'post'; // 设定评论目标为帖子
        this.newComment = ''; // 清空输入框
      }
    },

    // 显示回复输入框
    showReplyInput(commentIndex) {
      this.replyingTo = this.replyingTo === commentIndex ? null : commentIndex; // 切换显示与隐藏
      this.newReply = ''; // 清空回复框
    },

    // 提交回复
    async submitReply(commentIndex) {
      if (this.newReply.trim() === '') {
        uni.showToast({
          title: '回复内容不能为空',
          icon: 'none',
        });
        return;
      }

      try {
        const response = await commentApi.addComment({
          postId: this.postId,
          text: this.newReply,
          replyId: this.comments[commentIndex].id // 添加被回复评论的id
        });

        if (response && response.code === 1) {
          uni.showToast({
            title: '回复成功',
            icon: 'success'
          });

          this.newReply = ''; // 清空回复框
          this.replyingTo = null; // 隐藏回复框
          
          // 重新获取评论列表以更新数据
          await this.fetchComments();
        } else {
          throw new Error(response.msg || '回复失败');
        }
      } catch (error) {
        console.error('发布回复失败：', error);
        uni.showToast({
          title: '回复失败',
          icon: 'none'
        });
      }
    },

    // 删除评论
        handleCommentDelete(comment) {
          uni.showModal({
            title: '确认删除',
            content: '确定要删除这条评论吗？',
            success: async (res) => {
              if (res.confirm) {
                try {
                  const response = await commentApi.deleteComment({
                    id: comment.id
                  });
                  
                  if (response.code === 1) {
                    uni.showToast({
                      title: '删除成功',
                      icon: 'success',
                      complete: () => {
                        // 重定向到当前页面
                        uni.redirectTo({
                          url: `/pages/test01/test01?id=${this.postId}`
                        });
                      }
                    });
                  } else {
                    throw new Error(response.msg || '删除失败');
                  }
                } catch (error) {
                  console.error('删除评论失败:', error);
                  uni.showToast({
                    title: '删除失败',
                    icon: 'none'
                  });
                }
              }
            }
          });
        },

    // 删除回复
    deleteReply(commentIndex, replyIndex) {
      this.comments[commentIndex].replies.splice(replyIndex, 1); // 删除回复
      uni.showToast({
        title: '回复已删除',
        icon: 'success',
      });
    },
	    // 删除帖子
	    handleDelete() {
	      uni.showModal({
	        title: '确认删除',
	        content: '确定要删除这条帖子吗？',
	        success: async (res) => {
	          if (res.confirm) {
	            try {
					// 先跳转到 mine 页面
					             uni.switchTab({
					               url: '/pages/mine/mine'
					             });
	              console.log('删除帖子ID:', this.postId);
	              const response = await postApi.deletePost({ id: this.postId });
	              console.log('删除响应:', response);
	              
	              if (response.code === 1) {
	                uni.showToast({
	                  title: '删除成功',
	                  icon: 'success',
					   duration: 1500,
	                });
	              
	              } else {
	                throw new Error(response.msg || '删除失败');
	              }
	            } catch (error) {
	              console.error('删除失败:', error);
	              uni.showToast({
	                title: error.message || '删除失败',
	                icon: 'none'
	              });
	            }
	          }
	        }
	      });
	    },
    handleLike() {
      this.isLiked = !this.isLiked;
      this.likeCount += this.isLiked ? 1 : -1;
      // TODO: 调用点赞 API
    },

    handleShare() {
      uni.showActionSheet({
        itemList: ['分享到微信', '复制链接', '分享到朋友圈'],
        success: function (res) {
          // TODO: 处理分享逻辑
          uni.showToast({
            title: '分享功能开发中',
            icon: 'none'
          });
        }
      });
    }
  },
};
</script>

<style scoped>
/* 容器样式 */
.container {
  background-color: #f7f7f7;
  padding: 15px;
  height: 100%;
  box-sizing: border-box;
}

/* 帖子标题 */
.title {
  font-size: 25px;
  color: #333;
  font-weight: bold;
  margin-bottom: 15px;
}

/* 发布者的头像和昵称 */
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.post-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #007aff;
}

.post-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 评论用户的头像和昵称 */
.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

/* 帖子内容 */
.post-content .text {
  font-size: 16px;
  color: #555;
  margin-bottom: 20px;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 九宫格的图片和视频 */
.media-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 每行3个 */
  grid-gap: 12px;
}

.media-item {
  position: relative;
  padding-top: 100%;
  overflow: hidden;
  border-radius: 8px;
  background-color: #f5f5f5;
}

.media-image,
.media-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

/* 评论区 */
.comments {
  margin-top: 20px;
  padding: 0 15px;
}

.comments-header {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.comments-count {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 评论项样式 */
.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

/* 用户信息样式 */
.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.avatar.small {
  width: 30px;
  height: 30px;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  margin-bottom: 2px;
}

.comment-time {
  font-size: 12px;
  color: #999;
  display: block;
}

/* 评论内容样式 */
.comment-content {
  margin: 8px 0;
}

.comment-text {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

/* 评论操作区样式 */
.comment-actions {
  display: flex;
  gap: 20px;
  margin-top: 8px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 13px;
}

/* 回复区域样式优化 */
.replies {
  margin-left: 50px;
  margin-top: 12px;
  background-color: #f8f8f8;
  border-radius: 12px;
  padding: 12px;
}

.replies-header {
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.replies-count {
  font-size: 13px;
  color: #666;
}

.reply-item {
  padding: 10px 0;
  position: relative;
}

.reply-item:not(:last-child) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.reply-user {
  display: flex;
  align-items: flex-start;
  margin-bottom: 6px;
}

.reply-user-info {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 2px;
}

.reply-to {
  font-size: 12px;
  color: #999;
  margin: 0 4px;
}

.reply-content {
  margin-left: 40px;
  background-color: #fff;
  border-radius: 8px;
  padding: 8px 12px;
}

.reply-text {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

/* 输入框样式优化 */
.reply-input-container {
  margin-top: 10px;
  margin-left: 50px;
  background-color: #f8f8f8;
  border-radius: 12px;
  padding: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.reply-input {
  flex: 1;
  height: 36px;
  background-color: #fff;
  border-radius: 18px;
  padding: 0 15px;
  font-size: 14px;
  border: 1px solid #eee;
}

.reply-btn {
  min-width: 60px;
  height: 36px;
  line-height: 36px;
  background-color: #007AFF;
  color: #fff;
  border-radius: 18px;
  font-size: 14px;
  text-align: center;
  padding: 0 15px;
}

.reply-btn:active {
  opacity: 0.8;
}

/* 用户信息样式优化 */
.username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.comment-time {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

/* 头像样式优化 */
.avatar.small {
  width: 32px;
  height: 32px;
  border: 1px solid #eee;
}

/* 操作按钮样式优化 */
.action-item {
  padding: 4px 8px;
  border-radius: 15px;
  background-color: #f8f8f8;
  transition: background-color 0.2s;
}

.action-item:active {
  background-color: #eee;
}

.action-text {
  color: #666;
  font-size: 13px;
}


/* 输入框样式 */
.comment-input-container,
.reply-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 10px;
}

.comment-input,
.reply-input {
  flex: 1;
  height: 36px;
  background-color: #f5f5f5;
  border-radius: 18px;
  padding: 0 15px;
  font-size: 14px;
  border: none;
}

.submit-btn,
.reply-btn {
  padding: 0 15px;
  height: 36px;
  line-height: 36px;
  background-color: #007AFF;
  color: #fff;
  border-radius: 18px;
  font-size: 14px;
  border: none;
}

.submit-btn:active,
.reply-btn:active {
  opacity: 0.8;
}

/* 适配底部安全区域 */
.comment-input-container {
  padding-bottom: calc(10px + constant(safe-area-inset-bottom));
  padding-bottom: calc(10px + env(safe-area-inset-bottom));
}

.delete-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 8px 16px;
  background-color: #ff4444;
  color: white;
  border-radius: 4px;
  font-size: 14px;
}

.delete-btn:active {
  opacity: 0.8;
}

/* 操��栏样式 */
.action-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 15px 0;
  margin: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.action-bar .action-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 20px;
  border-radius: 20px;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
}

.action-bar .action-item:active {
  background-color: #e0e0e0;
  transform: scale(0.95);
}

.action-bar .iconfont {
  font-size: 20px;
  color: #666;
}

.action-bar .action-count {
  font-size: 14px;
  color: #666;
}

/* 点赞效果 */
.action-bar .liked {
  color: #ff6b6b;
}

/* 图标字体 */
@font-face {
  font-family: 'iconfont';
  src: url('//at.alicdn.com/t/font_12345678.woff') format('woff');
}

.iconfont {
  font-family: 'iconfont';
}

.icon-like:before {
  content: '\e669';
}

.icon-comment:before {
  content: '\e668';
}

.icon-share:before {
  content: '\e667';
}
</style>
